from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticatedOrReadOnly
from rest_framework import status
from django.db.models import F
from .models import BookingPost, BookingPostImage
from .serializers import BookingPostSerializer
from rest_framework.parsers import MultiPartParser
import math


class NearbyBookingPostList(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def get(self, request):
        user_lat = float(request.query_params.get('lat'))
        user_lng = float(request.query_params.get('lng'))
        radius_km = float(request.query_params.get('radius', 5))

        def haversine(lat1, lng1, lat2, lng2):
            R = 6371  # Earth radius in km
            dlat = math.radians(lat2 - lat1)
            dlng = math.radians(lng2 - lng1)
            a = math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) * math.sin(
                dlng / 2) ** 2
            return 2 * R * math.asin(math.sqrt(a))

        posts = BookingPost.objects.select_related('user').prefetch_related('images').all()
        filtered = [p for p in posts if haversine(user_lat, user_lng, p.latitude, p.longitude) <= radius_km]
        serializer = BookingPostSerializer(filtered, many=True)
        return Response(serializer.data)


class BookingPostCreate(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]

    def post(self, request):
        serializer = BookingPostSerializer(data=request.data)
        if serializer.is_valid():
            post = serializer.save(user=request.user)
            return Response(BookingPostSerializer(post).data, status=status.HTTP_201_CREATED)
        else:
            print(serializer.errors)  # 加这行
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


class BookingPostImageUpload(APIView):
    permission_classes = [IsAuthenticatedOrReadOnly]
    parser_classes = [MultiPartParser]

    def post(self, request, post_id):
        post = BookingPost.objects.get(id=post_id, user=request.user)
        image = request.FILES.get('image')
        if image:
            BookingPostImage.objects.create(post=post, image=image)
            return Response({'message': '上传成功'}, status=status.HTTP_201_CREATED)
        return Response({'error': '未上传图片'}, status=status.HTTP_400_BAD_REQUEST)


class BookingPostDetail(APIView):
    def get(self, request, post_id):
        try:
            post = BookingPost.objects.select_related('user').prefetch_related('images').get(id=post_id)
        except BookingPost.DoesNotExist:
            return Response({'error': '未找到'}, status=404)
        serializer = BookingPostSerializer(post)
        return Response(serializer.data)


